#!/bin/bash

# 20221224 bkw: wrapper script for asapconv, part of SBo asap build.

# Standalone player for SAP/etc files. asap's standalone player
# (asap-sdl) works, but mplayer supports pause and seeking, which
# makes it a lot nicer to use.
# I wrote this for my own use. Might as well include it in the SBo
# package, in case someone else wants it.

SELF="$( basename $0 )"

if [ "$#" = 0 -o "$1" = "--help" ]; then
  cat <<EOF
$SELF: play Atari chiptunes via mplayer.

Usage: $SELF [asapconv-options] filename

"filename" must be a file supported by asapconv; usually these are
*.sap files, but other formats are supported. Run "asapconv --help"
to see the list of supported file formats.

Any options given will be passed as-is to asapconv. This can be used
e.g. to select a subsong via "-s 2" or such.

$SELF is part of the SlackBuilds.org asap package, and is licensed
under the WTFPL.
EOF

  exit 0
fi

# asapconv can write to stdout, but mplayer can't seek when it's
# reading stdin, so use a file. The name has to end in .wav because
# asapconv insists on it. Tried using a FIFO, but in that case mplayer
# can't seek backwards. The wav file isn't all that big by modern
# standards (16MB for a 3-minute song), so it doesn't matter much.

# mktemp(3) says the -u option is "unsafe", so don't run this as root.
WAV="$( mktemp -u -t $SELF.XXXXXXXXXX.wav )"

asapconv -o "$WAV" "$@" || exit $?

# don't know for sure asapconv will *always* exit non-zero on failure,
# so check for the file's existence.
if [ -f "$WAV" ]; then
  mplayer "$WAV"
  rm -f "$WAV"
fi
